import React, { Component } from 'react'
import './adduser.scss'
import { Divider, Form, Input, Button, Checkbox, message, Select, Tooltip, Cascader, Upload, Modal } from 'antd'

import api from '../../../api'
import icon from '../../../config/iconConfig'
import residen from '../../../api/residen.json'
import getBase64 from '../../../utils/getBase64'
import { uploadAction } from '../../../constants'
const CheckboxGroup = Checkbox.Group;

const IconFont = icon.icon()
const { Option } = Select;

export default class AddUser extends Component {
    state = {
        previewVisible: false, // 标识是否显示大图预览Modal
        previewImage: '', // 大图的url
        fileList: [
            /*{
              uid: '-1', // 每个file都有自己唯一的id
              name: 'xxx.png', // 图片文件名
              status: 'done', // 图片状态: done-已上传, uploading: 正在上传中, removed: 已删除
              url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', // 图片地址
            },*/
        ],
        roleList: [],
        //身份信息
        residences: [],
        prefixSelector: (
            <Form.Item name="prefix" noStyle>
                <Select
                    style={{
                        width: 70,
                    }}
                >
                    <Option value="86">+86</Option>
                    <Option value="87">+87</Option>
                </Select>
            </Form.Item>
        ),
        formItemLayout: {
            labelCol: {
                xs: {
                    span: 24,
                },
                sm: {
                    span: 6,
                },
            },
            wrapperCol: {
                xs: {
                    span: 24,
                },
                sm: {
                    span: 12,
                },
            },
        },
        tailFormItemLayout: {
            wrapperCol: {
                xs: {
                    span: 24,
                    offset: 0,
                },
                sm: {
                    span: 16,
                    offset: 8,
                },
            },
        }
    }
    // //发送服务器请求
    postData = async (values) => {
        const { roleList,fileList } = this.state
        let role_id = ""
        console.log(fileList[0]);
        roleList.map(item => {
            if (item.name === values.roleselect) {
                role_id = item.roleID
            }
        })
        let time = new Date().toLocaleString();
        values = { ...values, roleselect: role_id,avatar:fileList[0]?fileList[0].url:'' }
        console.log('Received values of form: ', values);
        api.signin.sign(values, time).then(res => {
            console.log(res);
            if (res.data.msg) {
                message.error(res.data.msg);
            }
            if (res.data.data) {
                message.success("注册成功");
            }
        })
    }
    
    /*
  获取所有已上传图片文件名的数组
   */
  getImgs  = () => {
    return this.state.fileList.map(file => file.name)
  }

  /*
  隐藏Modal
   */
  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async file => {
    console.log('handlePreview()', file)
    if (!file.url && !file.preview) {
        file.preview = await getBase64.getBase64(file.originFileObj);
      }
    // 显示指定file对应的大图
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };
  /*
  file: 当前操作的图片文件(上传/删除)
  fileList: 所有已上传图片文件对象的数组
   */
  handleChange = async ({ file, fileList }) => {
    console.log('handleChange()', file.status, fileList.length, file===fileList[fileList.length-1])

    // 一旦上传成功, 将当前上传的file的信息修正(name, url)
    if(file.status==='done') {
      const result = file.response  // {status: 0, data: {name: 'xxx.jpg', url: '图片地址'}}
      if(result.status===0) {
        message.success('上传图片成功!')
        const {name, url} = result.data
        file = fileList[fileList.length-1]
        file.name = name
        file.url = url
      } else {
        message.error('上传图片失败')
      }
    } else if (file.status==='removed') { // 删除图片
      const result = await api.user.reqDeleteImg(file.name)
      console.log(result);
      if (result.data.status===0) {
        message.success('删除图片成功!')
      } else {
        message.error('删除图片失败!')
      }
    }

    // 在操作(上传/删除)过程中更新fileList状态
    this.setState({ fileList })
  };

    async componentDidMount() {
        console.log(residen);
        const { residences, roleList } = this.state
        this.setState({ residences: residen.provinces.province })
        let roledata = await api.role.roledata()
        console.log(roledata);
        this.setState({ roleList: roledata.data.data })
    }
    render() {
        const { residences, prefixSelector, formItemLayout, tailFormItemLayout, roleList,previewVisible,previewImage,fileList } = this.state
        const uploadButton = (
            <div>
                <IconFont type="icon-zengjiatianjiajiajian" />
                <div>Upload</div>
            </div>
        );
        return (
            <div id="add-user">
                <Divider />
                <header>添加用户</header>
                <Divider />
                <Form
                    {...formItemLayout}
                    name="register"
                    onFinish={this.postData}
                    initialValues={{
                        residence: ['浙江省', '杭州市', '余杭区'],
                        prefix: '86',
                        roleselect: "普通用户",
                    }}
                >
                    <Form.Item
                        name="email"
                        label="E-mail"
                        rules={[
                            {
                                type: 'email',
                                message: '邮箱格式不正确!',
                            },
                            {
                                required: true,
                                message: '请输入邮箱号!',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="phone"
                        label="电话号码"
                        rules={[
                            {
                                required: true,
                                message: '请输入电话号码!',
                            },
                            {
                                max: 11,
                                message: '请输入正确的电话号码'
                            },
                            {
                                pattern: /^[0-9]+$/,
                                message: '请输入正确的电话号码'
                            }
                        ]}
                    >
                        <Input
                            addonBefore={prefixSelector}
                            style={{
                                width: '100%',
                            }}
                        />
                    </Form.Item>
                    <Form.Item
                        name="password"
                        label="密码"
                        rules={[
                            {
                                required: true,
                                message: '请输入密码!',
                            },
                            {
                                pattern: /^[a-zA-Z]\w{5,17}$/,
                                message: '以字母开头，长度在6~18之间，不包含特殊字符，18之间，不包含特殊字符，可以使用下划线!',
                            },
                        ]}
                        help="以字母开头，长度在6~18之间，不包含特殊字符，可以使用下划线"
                    >
                        <Input.Password />
                    </Form.Item>

                    <Form.Item
                        name="confirm"
                        label="确认密码"
                        dependencies={['password']}
                        rules={[
                            {
                                required: true,
                                message: '请确认密码!',
                            },
                            ({ getFieldValue }) => ({
                                validator(_, value) {
                                    if (!value || getFieldValue('password') === value) {
                                        return Promise.resolve();
                                    }

                                    return Promise.reject('两次密码不相同!');
                                },
                            }),
                        ]}
                    >
                        <Input.Password />
                    </Form.Item>

                    <Form.Item
                        name="nickname"
                        label={
                            <span>
                                昵称&nbsp;
                                        <Tooltip title="别的名称去称呼你?也是唯一的">
                                    <IconFont type="icon-bangzhu" />
                                </Tooltip>
                            </span>
                        }
                        rules={[
                            {
                                required: true,
                                message: '请输入昵称!',
                                whitespace: true,
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        name="residence"
                        label="所在地区"
                        rules={[
                            {
                                type: 'array',
                                required: true,
                                message: '选择所在地区!',
                            },
                        ]}
                    >
                        <Cascader fieldNames={{ label: 'ssqname', value: 'ssqname' }} options={residences} />
                    </Form.Item>
                    <Form.Item
                        name="roleselect"
                        label="角色选择"
                        rules={[
                            {
                                required: true,
                                message: '选择角色!',
                            },
                        ]}
                    >
                        <Select>
                            {
                                roleList.map(item => {
                                    if (item.name !== "admin") {
                                        return <Option key={item.roleID} value={item.name}>{item.name}</Option>
                                    }
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        label="头像设置"
                        rules={[
                            {
                                required: true,
                                message: '设置头像!',
                            },
                        ]}
                    >
                        <Upload
                            action={uploadAction} /*上传图片的接口地址 http://jinxinapp.cn/manage/img/upload */
                            accept='image/*'  /*只接收图片格式*/
                            name="avatar"
                            listType="picture-card"  /*卡片样式*/
                            fileList={fileList}  /*所有已上传图片文件对象的数组*/
                            onPreview={this.handlePreview}
                            onChange={this.handleChange}
                        >
                            {fileList.length >= 1? null : uploadButton}
                        </Upload>
                        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                            <img alt="example" style={{ width: '100%' }} src={previewImage} />
                        </Modal>
                    </Form.Item>
                    <Form.Item {...tailFormItemLayout}>
                        <Button type="primary" htmlType="submit">添加用户</Button>
                    </Form.Item>
                </Form>
            </div>
        )
    }
}
